import { isServer, isDocumentVisibility } from './index'
import type { ListenerType, EventFunc, ListenersSet } from './types'

export const FOCUS_LISTENER: ListenersSet = new Set()
export const VISIBLE_LISTENER: ListenersSet = new Set()

export const subscribe = (listenerType: ListenerType, event: EventFunc) => {
  let listeners: ListenersSet
  switch (listenerType) {
    case 'FOCUS_LISTENER':
      listeners = FOCUS_LISTENER
      break
    case 'VISIBLE_LISTENER':
      listeners = VISIBLE_LISTENER
      break
  }

  if (listeners.has(event)) return
  listeners.add(event)

  return () => {
    listeners.delete(event)
  }
}

const observer = (listeners: ListenersSet) => {
  listeners.forEach(event => event())
}

if (!isServer && window?.addEventListener) {
  window.addEventListener(
    'visibilitychange',
    () => {
      if (isDocumentVisibility()) {
        observer(VISIBLE_LISTENER)
      }
    },
    false
  )
  window.addEventListener('focus', () => observer(FOCUS_LISTENER), false)
}
